//
//  DDTabEncryptionHDVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/3.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDTabEncryptionHDVC.h"
#import "GlobalDefine.h"
#import "UIImageView+WebCache.h"
#import "UIViewController+CWPopup.h"
#import "DDPopResultVC.h"
#import "DDNetWorkAPIClient.h"

#define KEY_IMAGE @"IMAGE"
#define KEY_LABEL @"LABEL"
#define KEY_OPTION @"OPTION"
@interface DDTabEncryptionHDVC ()

@property(nonatomic,strong)NSMutableArray *datas;
@property(nonatomic,strong)NSMutableArray *keys;
@property(nonatomic,strong)NSString *questionType;
@end

@implementation DDTabEncryptionHDVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}

- (void)createUI
{
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissPopup)];
    tapRecognizer.numberOfTapsRequired = 1;
    tapRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapRecognizer];
     self.automaticallyAdjustsScrollViewInsets = NO;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        CGRect rect = self.view.frame;
        rect.origin = CGPointMake(rect.origin.x, rect.origin.y - 20);
        rect.size = CGSizeMake(rect.size.width, rect.size.height);
        self.view.frame = rect;
    }
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    self.view.backgroundColor = RGB(245, 245, 245);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    //自定义TAB BAR UI
    [self addNavigatorTitle:NSLocalizedString(self.title, nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
        //[self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self AddRightBtnAction:@"提交" normal:nil selected:nil action:^{
        
        
        DDPopResultVC *pop = [[DDPopResultVC alloc] init];
        
        [self presentPopupViewController:pop animated:YES completion:^(void) {
            NSLog(@"popup view presented");
        }];
        
        pop.SubmitButtonBlock = ^(NSString *name,NSString *schoolName,NSString *clzssName){
            DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
           //DDSharedUser *sharedUser = [DDSharedUser shared];
            //if (sharedUser.userInfo.name==nil ||[@"" isEqualToString:sharedUser.userInfo.name]) {
            //提交用户信息
//            NSDictionary *params = @{@"school":schoolName,@"name":name,@"clzss":clzssName};
            [network userEdit:@"" nickName:@"" name:name gender:@"" birthday:@"" phoneNum:@"" school:schoolName grade:@"" clzss:clzssName recent:@"" completionBlock:^(BOOL isSuccess, NSString *message, NSString *status) {
                //            [network userEdit:params completionBlock:^(BOOL isSuccess,NSString *message, NSString *status) {
                DDSharedUser *sharedUser = [DDSharedUser shared];

                sharedUser.userInfo.name = name;
                sharedUser.userInfo.school = schoolName;
                sharedUser.userInfo.clzss = clzssName;
            }];
            
            //}
            
            //提交题目
            [network mainAnswerSave:@{@"topicId":_topicID,@"qid":_question.id,@"answer":@"A",@"costSeconds":@"10"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                    NSLog(@"%@",object);
                if (object) {
                    [self dismissPopup];
                }
                [MBProgressHUD showMessag:message toView:self.view];
                
            }];
        };
       
        
    }];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0.1)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0.1)];
}

- (void)createData
{
    _datas = [NSMutableArray array];
    _keys = [NSMutableArray array];
    
    NSMutableArray *imageArray = [NSMutableArray array];
    NSMutableArray *labelArray = [NSMutableArray array];
    NSMutableArray *optionArray = [NSMutableArray array];
    
    //DDTopicDataCellModel *model =  _topic.list[0];
    //DDTopicQuestion *question = model.questions[0];
    NSArray *bodyList = _question.body;
    _questionType = _question.typeName;
    
    
    UIView *imageView = [[UIView alloc] initWithFrame:CGRectMake(10, 64, self.view.frame.size.width-20, 300)];
    [self.view addSubview:imageView];
    optionArray = [NSMutableArray arrayWithArray:_question.options];
    
    for (DDTopicQuestionBody *body in bodyList) {
        if ([body.type isEqualToString:@"IMAGE"]) {
            [imageArray addObject:body.url];
        }
        if ([body.type isEqualToString:@"TEXT"]) {
            [labelArray addObject:body.text];
        }
    }
    
    
    
    if (imageArray.count > 0) {
        [_datas addObject:imageArray];
        [_keys addObject:KEY_IMAGE];
    }
    if (labelArray.count > 0) {
        [_datas addObject:labelArray];
        [_keys addObject:KEY_LABEL];
    }
    if (optionArray.count > 0) {
        [_datas addObject:optionArray];
        [_keys addObject:KEY_OPTION];
    }
    
    [self.tableView reloadData];
    
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = _datas[indexPath.row];
    if ([_keys[indexPath.section] isEqualToString:KEY_IMAGE]) {
        return 300 * array.count;
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_LABEL])
    {
        return 100 * array.count;
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_OPTION])
    {
        if ([_questionType isEqualToString:@"单选"] ) {
            return 38*array.count + 150;
        }
        else
        {
            return 300;
        }
    }
    return 0;
}


- (CGSize)autoLabelString:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(view.frame.size.width - 10,2000);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    NSArray *array = _datas[indexPath.section];
    if ([_keys[indexPath.section] isEqualToString:KEY_IMAGE]) {
        for (int i = 0 ; i < array.count ; i++)
        {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0 + (300*i), tableView.frame.size.width - 20, 300)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:array[i]] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
            [cell.contentView addSubview:imageView];
        }
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_LABEL])
    {
        for (int i = 0 ; i < array.count ; i++)
        {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10 + (100*i), tableView.frame.size.width-20, 24)];
            label.text = array[0];
            [cell.contentView addSubview:label];
        }
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_OPTION])
    {
        UILabel *typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 32)];
        typeLabel.text = [NSString stringWithFormat:@"(%@)", _questionType];
        [cell.contentView addSubview:typeLabel];
        for (int i = 0; i < array.count; i++) {
            DDTopicQuestionOption *option = array[i];
            UIButton *optionButton = [UIButton buttonWithType:UIButtonTypeCustom];
            optionButton.frame = CGRectMake(10, [self yPostiong:typeLabel sp:10 + (44*i)], 38, 38);
            [optionButton setTitle:option.label forState:UIControlStateNormal];
            [optionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            optionButton.tag = i+1000;
            [optionButton addTarget:self action:@selector(optionSelect:) forControlEvents:UIControlEventTouchUpInside];
            [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg灰"] forState:UIControlStateNormal];
            [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg橙"] forState:UIControlStateSelected];
            [cell.contentView addSubview:optionButton];
            
            DDTopicQuestionOptionContent *content = option.content[0];
            if ([content.type isEqualToString:@"TEXT"])
            {
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y+5, tableView.frame.size.width-100, 24)];
                label.text = content.text;
                label.textColor = [UIColor blackColor];
                [cell.contentView addSubview:label];
            }
            else if ([content.type isEqualToString:@"IMAGE"])
            {
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y+5, 32, 32)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:content.url] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]options:SDWebImageRefreshCached];
                [cell.contentView addSubview:imageView];
            }
            
        }
    }
    
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@",@"123");
}


#pragma mark - 私用方法
-(void)optionSelect:(UIButton *)button
{
    button.selected = !button.selected;
    _result = [NSString stringWithFormat:@"%ld",button.tag - 1000];
}

-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}

- (void)dismissPopup {
    if (self.popupViewController != nil) {
        [self dismissPopupViewControllerAnimated:YES completion:^{
            NSLog(@"popup view dismissed");
        }];
    }
}


// so that tapping popup view doesnt dismiss it
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return touch.view != self.popupViewController.view;
}

@end
